/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package rsync

import (
	"errors"

	"gitee.com/banggua/ggtsync/cmdutil"
	"gitee.com/banggua/ggtsync/config"
	"gitee.com/banggua/ggtsync/logger"
	"gopkg.in/yaml.v2"
)

const (
	PluginName = "rsync"
)

type rsyncPlugin struct{}

var (
	DefaultPlugin = &rsyncPlugin{}
)

func (rp *rsyncPlugin) Test(args map[string]string) error {
	if len(args) != 2 {
		logger.Errorf("%v", errors.New("invalid arguments"))
		return errors.New("invalid arguments")
	}
	// 1 path
	if _, exist := args["path"]; !exist {
		logger.Errorf("%v", errors.New("args.path field does not exist"))
		return errors.New("args.path field does not exist")
	}
	// 2 remote
	if _, exist := args["remote"]; !exist {
		logger.Errorf("%v", errors.New("args.remote field does not exist"))
		return errors.New("args.remote field does not exist")
	}
	return nil
}

func (rp *rsyncPlugin) Templet() string {
	var chmodYaml = &config.Plugin{
		Name:  PluginName,
		Order: 1,
		Args: map[string]string{
			"path":   "/mirrors",
			"remote": "root@127.0.0.1:/",
		},
	}
	out, _ := yaml.Marshal(&chmodYaml)
	return string(out)
}

func (rp *rsyncPlugin) Handle(project *config.Project, args map[string]string) error {
	err := cmdutil.Run("", "rsync", "-avz", "--delete", args["path"], args["remote"])
	if err != nil {
		logger.Errorf("%v", err)
		return err
	}
	return nil
}
